﻿using System.Windows.Forms;
using System.Windows.Forms.Integration;
using Fiddler;
using Hardanger.Model;
using Hardanger.View;
using Hardanger.Utils;
using System.Windows;
using System;
using System.Resources;
using Hardanger.ViewModel;
using System.IO;
using System.Text;


[assembly: Fiddler.RequiredVersion("2.3.5.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
namespace Hardanger.Controller
{
	public partial class HardangerCore : IFiddlerExtension, IHandleExecAction, IAutoTamper3
	{
        static private TabPage oPage;
        static private ElementHost host;
        private static char[] getSeparator = { '?' };
		static private HardangerViewModel _addOnViewModel = null;
		static public HardangerViewModel AddOnViewModel
		{
				  get
				  {
					  if (_addOnViewModel == null)
					  {
						  _addOnViewModel = new HardangerViewModel();
					  }
					  return _addOnViewModel;
				  }			
		}
		
        public static Proxy FiddlerProxy
        {
            get { return FiddlerApplication.oProxy; }
        }
		public void OnLoad()
		{
            LoadMainWindow();
			FiddlerApplication.CalculateReport += HandleSelectedSessions;
		}
		
		public void OnBeforeUnload() { }

        public void LoadMainWindow()
        {
            oPage = new TabPage("Hardanger");
            oPage.ImageIndex = (int)Fiddler.SessionIcons.Secure;
            
            host = new ElementHost();
            host.Dock = DockStyle.Fill;
            HardangerController.HardangerCoreControl.InitializeComponent();
            //HardangerController.HardangerCoreControl.DataContext = "{Binding Source={StaticResource SessionManager.Current}, Path=SelectedSession}";
			HardangerController.HardangerCoreControl.DataContext = AddOnViewModel;
            host.Child = HardangerController.HardangerCoreControl;
            oPage.Controls.Add(host);
            FiddlerApplication.UI.tabsViews.TabPages.Add(oPage);
        }


        private static void HandleSelectedSessions(Session[] sessions)
        {
            if (sessions.Length > 0)
            {
				if (!sessions[0].isTunnel)
				{
					//MemoryStream strStream = new MemoryStream();
					//sessions[0].WriteRequestToStream(false, true, strStream);
				
					string body = Encoding.UTF8.GetString(sessions[0].RequestBody);
					string request = sessions[0].oRequest.headers.ToString(true, true, true) + body;
					AddOnViewModel.SelectedSession = FiddlerSessionParser.ParseFiddlerSession(sessions[0].id, sessions[0].hostname, sessions[0].port, sessions[0].isHTTPS, request);
				}
            }
        }
	}
}

